package com.ada.service;

import com.ada.handler.UserServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Service;


@Service(value = "UserService")
public class UserServiceImpl implements UserService {
    public String sayHello(String word) {
        System.out.println("调用成功-参数：" + word);
        return "success";
    }

    public UserServiceImpl() {
        startServer("localhost", 8990);
    }

    //启动netty的服务器程序
    public static void startServer(String hostName, int port) {
        try {
            NioEventLoopGroup bossGroup = new NioEventLoopGroup();
            NioEventLoopGroup workGroup = new NioEventLoopGroup();
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws
                                Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new StringDecoder());
                            p.addLast(new StringEncoder());
                            p.addLast(new UserServerHandler());
                        }
                    });
            bootstrap.bind(hostName, port).sync();
            System.out.println("=================>>>>> server Start at :" + hostName + ":" + port);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
